﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CXMLStudioIDE.DataAccessLayer;
using CXMLStudioIDE.Common;
using CXMLStudioIDE.Common.Entities;
using System.Threading;
using System.Collections;
using CXMLStudioIDE.BusinessLayer;

namespace CXMLStudioIDE.Forms
{
    public partial class NewProjectFromExistingForm : Form
    {
        MainForm m_parent;
        private BindingSource m_bindingsource;
        private CXMLStudioIDE.DataAccessLayer.SolutionManagerDAL dal = null;
        private int SelectedProjectID = -1;
        private Project selectedproject = null;
        private Solution m_solution = null;

        public NewProjectFromExistingForm(MainForm parent)
        {
            InitializeComponent();
            m_parent = parent;
            dal = new SolutionManagerDAL();
        }

        private void OpenProjectForm_Load(object sender, EventArgs e)
        {
            m_bindingsource = new BindingSource();
            dsAddProject = dal.GetProjectsInScopeAndContext();
            RemoveCurrentProjects();
            m_bindingsource.DataSource = dsAddProject;
            m_bindingsource.DataMember = dsAddProject.Tables[0].TableName;
            dgvAddProject.DataSource = m_bindingsource;
            if (dgvAddProject.Columns.Count != 0)
            {
                ConfigureAddProjectGridView();
                PopulateCombo(this.cmbScope, "ScopeName", "ScopeID");
                PopulateCombo(this.cmbContext, "ContextName", "ContextID");
            }
            m_solution = m_parent.m_SolutionManager.m_solution;

        }
        /** Remove Projects currently assigned to User Solution **/
        private void RemoveCurrentProjects()
        {
            ArrayList rowstodelete = new ArrayList();
            if (dsAddProject.Tables.Count > 0)
            {
                foreach (DataRow row in dsAddProject.Tables[0].Rows)
                {
                    int project_id = (int)row["ProjectID"];
                    Project p = m_parent.m_SolutionManager.m_solution.Projects.GetProjectByID(project_id);
                    if (p != null)
                    {
                        rowstodelete.Add(row);
                    }
                }
                foreach (DataRow rdel in rowstodelete)
                {
                    dsAddProject.Tables[0].Rows.Remove(rdel);
                }
            }
        }

        /** Generic method to populate Scope and Context dropdowns with unique values **/
        private void PopulateCombo(ComboBox cmb, string sZ_DisplayMember, string sZ_ValueMember)
        {
            DataTable table = new DataTable();
            table.Columns.Add(sZ_ValueMember, typeof(int));
            table.Columns.Add(sZ_DisplayMember, typeof(string));
            ArrayList scopes = new ArrayList();
            table.Rows.Add("0", " -- All -- ");
            foreach (DataRow row in dsAddProject.Tables[0].Rows)
            {
                int scopeID = (int)row[sZ_ValueMember];
                if (!scopes.Contains(scopeID))
                {
                    table.Rows.Add(scopeID, row[sZ_DisplayMember]);
                }
                scopes.Add(scopeID);
            }
            cmb.DataSource = table;
            cmb.DisplayMember = sZ_DisplayMember;
            cmb.ValueMember = sZ_ValueMember;
        }

        private void ConfigureAddProjectGridView()
        {
            dgvAddProject.Columns["ProjectID"].Visible = false;
            dgvAddProject.Columns["ScopeID"].Visible = false;
            dgvAddProject.Columns["ContextID"].Visible = false;
            dgvAddProject.Columns["ProjectName"].DisplayIndex = 0;
            dgvAddProject.Columns["ScopeName"].DisplayIndex = 1;
            dgvAddProject.Columns["ContextName"].DisplayIndex = 2;
            dgvAddProject.AutoResizeColumns();

        }

        /** Set visible only EntityName and Version then autoresize columns**/
        private void ConfigureEntitiesGridView()
        {
            foreach (DataGridViewColumn col in dgvEntitiesInProject.Columns)
            {
                if (!col.Name.Equals("EntityTypeName") && !col.Name.Equals("Version") &&
                    !col.Name.Equals("EntityTypeContextName"))
                {
                    col.Visible = false;
                }
            }
            dgvEntitiesInProject.AutoResizeColumns();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            int i_SolutionID = m_parent.m_SolutionManager.m_solution.ID;
            if (i_SolutionID > 0 && selectedproject != null && txtProjectName.Text.Length > 0)
            {
                
                if (m_solution != null && m_solution.Projects != null)
                {
                    DataSet ds = dal.SaveNewProjectFromExisting(txtProjectName.Text,i_SolutionID, SelectedProjectID);
                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        selectedproject.ID = (int)ds.Tables[0].Rows[0].ItemArray[0];
                    }
                    else
                    {
                        MessageBox.Show(this, "Could not save new Project", "CXMLStudioIDE", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    m_parent.m_SolutionManager.m_solution.AddProjectToSolution(selectedproject);
                }
                else
                {
                    m_parent.m_SolutionManager.m_project = selectedproject;
                    m_parent.EnabledMenuItem("menuItemCloseProject", true);
                }
                //m_parent.DsBusinessEntityCode = this.dsBusinessEntity;
                m_parent.CloseSolution();
                m_parent.m_SolutionManager.OpenSolution(m_solution);
                m_parent.UpdateMainForm();
                this.Dispose();
            }
            else
            {
                MessageBox.Show(this, "Please select a Project and enter name", "CXMLStudioIDE", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void dgvOpenSolution_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            btnAdd_Click(sender, e);
        }

        private void dgvOpenSolution_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btnAdd_Click(sender, e);
            }
        }
        private string GetFilterString()
        {
            string filter = null;
            if (cmbScope.SelectedIndex > 0 && cmbContext.SelectedIndex == 0)
            {
                filter = "ScopeID =" + cmbScope.SelectedValue;
            }
            if (cmbScope.SelectedIndex == 0 && cmbContext.SelectedIndex > 0)
            {
                filter = "ContextID =" + cmbContext.SelectedValue;
            }
            if (cmbScope.SelectedIndex > 0 && cmbContext.SelectedIndex > 0)
            {
                filter = "ScopeID =" + cmbScope.SelectedValue + " AND ContextID=" + cmbContext.SelectedValue;
            }
            return filter;
        }
        private void SelectedIndexChanged(object sender, EventArgs e)
        {
            string filter = GetFilterString();
            if (filter != null)
            {
                m_bindingsource.Filter = filter;
            }
            else
            {
                m_bindingsource.RemoveFilter();
            }
        }

        private void dgvAddProject_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection rc = dgvAddProject.SelectedRows;
            int project_id = -1;
            selectedproject = null;
            foreach (DataGridViewRow row in rc)
            {
                project_id = (int)row.Cells["ProjectId"].Value;
                SelectedProjectID = project_id;
                selectedproject = new Project();
                selectedproject.Name = row.Cells["ProjectName"].Value.ToString();
                selectedproject.Scope.ID = (int)row.Cells["ScopeID"].Value;
                selectedproject.Scope.Name = row.Cells["ScopeName"].Value.ToString();
                selectedproject.Context.ID = (int)row.Cells["ContextID"].Value;
                selectedproject.Context.Name = row.Cells["ContextName"].Value.ToString();

            }
            dsEntitiesInProject = dal.GetEntitiesForProject(project_id);
            dgvEntitiesInProject.DataSource = dsEntitiesInProject.Tables[0];
            ConfigureEntitiesGridView();
        }

        private void dgvEntitiesInProject_MouseDown(object sender, MouseEventArgs e)
        {
            dgvEntitiesInProject.ClearSelection();
        }

        private void dgvEntitiesInProject_SelectionChanged(object sender, EventArgs e)
        {
            /* Since there is no entity selection then just clear it **/
            dgvEntitiesInProject.ClearSelection();
        }

    }
}
